//
//  ListMaintenanceAttachmentViewController.m
//  FMS
//
//  Created by Steven on 11/14/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "ListMaintenanceAttachmentViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "DetailedDocumentViewController.h"

@implementation CustomImageCell
@synthesize detailDict;

- (void) selectItem:(id)sender {
    isSelect = !isSelect;
    if (isSelect) {
        [self setImage:[UIImage imageNamed:@"btnTick.png"] forState:UIControlStateNormal];
    }
    else {
        [self setImage:nil forState:UIControlStateNormal];
    }
}

@end

@interface ListMaintenanceAttachmentViewController ()

@end

@implementation ListMaintenanceAttachmentViewController
@synthesize parent;
@synthesize maintenanceTypeId;
@synthesize maintenanceId;
@synthesize permissionDict;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        parent = _parent;
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
    }
    return self;
}

- (IBAction)handleDelete:(id)sender {
    NSString *msg = @"";

    if ([itemIndexSet count] > 1) {
        msg = [dictLanguage objectForKey:@"maintenance-mgmt.attach-document.delete-some-documents"];
        
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:[dictLanguage objectForKey:@"general.no"],[dictLanguage objectForKey:@"general.yes"], nil];
        [dialog show];
    }
    else if ([itemIndexSet count] == 1) {
        msg = [dictLanguage objectForKey:@"maintenance-mgmt.attach-document.delete-a-document"];
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:[dictLanguage objectForKey:@"general.no"],[dictLanguage objectForKey:@"general.yes"], nil];
        [dialog show];
    }
    else {
        msg = [dictLanguage objectForKey:@"maintenance-mgmt.attach-document.require-select-document-to-delete"];
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles: nil];
        [dialog show];
    }
}
- (IBAction)handleSelect:(id)sender {
    isEditable = !isEditable;
    _btnDelete.hidden = !isEditable;
    
    if (!isEditable) {
        [self.btnSelect setTitle:@"Select" forState:UIControlStateNormal];
        //loop all array and set NO for isSelected
        for (int i=0;i < [mainArray count];i++) {
            NSMutableDictionary *dict = [mainArray objectAtIndex:i];
            [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isSelected"];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
            CustomImageCell *imgView = (CustomImageCell*)[cell.contentView viewWithTag:99+indexPath.row];
            [imgView setImage:nil forState:UIControlStateNormal];
        }
        [itemIndexSet removeAllIndexes];
    }
    else {
        [self.btnSelect setTitle:@"Cancel" forState:UIControlStateNormal];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSIndexSet *tmpIndexSet = [itemIndexSet mutableCopy];
        NSMutableArray *tmpDocumentArray = [mainArray mutableCopy];
        
        [mainArray removeObjectsAtIndexes:itemIndexSet];
        [itemIndexSet removeAllIndexes];
        [self.collectionView reloadData];
        
        //delete document from database
        //get index in indexSet
        [tmpIndexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
            NSMutableDictionary *dict = [tmpDocumentArray objectAtIndex:idx];
            NSError *error;
            
            [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[dict objectForKey:@"_id"] error:&error];
            if (!error) {
                NSLog(@"delete document success");
            }
        }];
        [self performSelector:@selector(reloadAfterDelete) withObject:self afterDelay:0.5];
    }
}

- (void) reloadAfterDelete {
    if ([mainArray count] == 0)
        [(MaintenanceDetailedViewController*)parent dismissPopoverController];
    [(MaintenanceDetailedViewController*)parent reloadMaintenanceAttachment];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    mainArray = [NSMutableArray arrayWithCapacity:1];
    itemIndexSet = [NSMutableIndexSet indexSet];

    _btnDelete.hidden = YES;
    
    [_btnSelect setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateNormal];
    
    _lbTitle.center = CGPointMake(self.view.frame.size.width/2, 22);
    _lbTitle.textColor = APPLE_BLUE_COLOR;
    
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"FlickrCell"];
    
    NSMutableArray *tmpArray = [CouchBaseLiteLib listAttachmentByMaintenance:maintenanceId andType:maintenanceTypeId];
    for (int i=0;i < [tmpArray count];i++) {
        NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
        [dict setObject:[NSNumber numberWithBool:NO] forKey:@"isSelected"];
        [mainArray addObject:dict];
    }
    
    [self setContentSizeForViewInPopover:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
    
    BOOL isUpdate = [[permissionDict objectForKey:@"update"] boolValue];
    if (!isUpdate) {
        _btnSelect.hidden = YES;
    }
}

#pragma mark - UICollectionView Datasource
// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [mainArray count];
}
// 2
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}
// 3
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"FlickrCell" forIndexPath:indexPath];

    /*
    NSString *imageUrl = [dict objectForKey:@"imageUrl"];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary assetForURL:[NSURL URLWithString:imageUrl] resultBlock: ^(ALAsset *asset){
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        CGImageRef imageRef = [representation fullResolutionImage];
        if (imageRef) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
            imageView.image = [UIImage imageWithCGImage:imageRef scale:representation.scale orientation:representation.orientation];
            [cell.contentView insertSubview:imageView atIndex:0];
        }
    } failureBlock: ^(NSError *myerror){
        // Handle failure.
        NSData *imageData = nil;
        if (document.currentRevision) {
            CBLAttachment *attach = [document.currentRevision attachmentNamed:[dict objectForKey:@"fileName"]];
            imageData = [attach body];
        }
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
        imageView.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
        [cell.contentView insertSubview:imageView atIndex:0];
    }];
    */
    
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    CustomImageCell *imageView = (CustomImageCell*)[cell.contentView viewWithTag:99 + indexPath.row];
    if (imageView == nil) {
        CBLDocument *document = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[dict objectForKey:@"_id"]];
        NSData *imageData = nil;
        if (document.currentRevision) {
            CBLAttachment *attach = [document.currentRevision attachmentNamed:[dict objectForKey:@"fileName"]];
            imageData = [attach body];
        }
        
        imageView = [CustomImageCell buttonWithType:UIButtonTypeCustom];
        imageView.tag = 99 + indexPath.row;
        imageView.detailDict = dict;
        imageView.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
        imageView.imageEdgeInsets = UIEdgeInsetsMake(0., 88, -66, 0.); //top,left,bottom,right
        [imageView setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
        [imageView addTarget:self action:@selector(selectItem:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:imageView];
    }
    else {
        [cell.contentView addSubview:imageView];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    // TODO: Select Item
//    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
//    BOOL isSelected = [[dict objectForKey:@"isSelected"] boolValue];
//    [dict setObject:[NSNumber numberWithBool:!isSelected] forKey:@"isSelected"];
//    
//    NSArray *indexPathArray = [NSArray arrayWithObjects:indexPath, nil];
//    [collectionView reloadItemsAtIndexPaths:indexPathArray];
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    // TODO: Deselect item
}

- (void) selectItem:(CustomImageCell*)sender {
    int index = sender.tag - 99;
    NSMutableDictionary *dict = [mainArray objectAtIndex:index];
    
    if (isEditable) {
        //reverse the current value of isSelected
        BOOL isSelect = ![[dict objectForKey:@"isSelected"] boolValue];
        [dict setObject:[NSNumber numberWithBool:isSelect] forKey:@"isSelected"];
        if (isSelect) {
            [sender setImage:[UIImage imageNamed:@"btnTick.png"] forState:UIControlStateNormal];
            [itemIndexSet addIndex:index];
        }
        else {
            [sender setImage:nil forState:UIControlStateNormal];
            [itemIndexSet removeIndex:index];
        }
    }
    else {
        //view detail image
        NSLog(@"view detail");
        CBLDocument *document = [[CouchBaseLiteLib sharedCouchBaseLite] getDocumentById:[dict objectForKey:@"_id"]];
        NSData *imageData = nil;
        if (document.currentRevision) {
            CBLAttachment *attach = [document.currentRevision attachmentNamed:[dict objectForKey:@"fileName"]];
            imageData = [attach body];
            
            DetailedDocumentViewController *controller = [[DetailedDocumentViewController alloc] initWithNibName:@"DetailedDocumentViewController" bundle:nil itemType:0 parent:self];
            controller.documentImage = [UIImage imageWithData:imageData];
            [self presentViewController:controller animated:YES completion:nil];
        }
    }
}

#pragma mark – UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(130, 130);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

@end
